package com.xu.cloud.auth.component.oauth;

import com.xu.cloud.auth.enums.ThirdPartyEnum;
import com.xu.cloud.auth.pojo.bo.OAuth2AccessTokenBO;
import com.xu.cloud.auth.pojo.bo.OAuth2UserInfo;
import com.xu.cloud.common.util.RestTemplateUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

/**
 * github oauth2 授权实现类
 *
 * @author xuguan
 * @since 2025/2/28
 */
@Component
public class GithubOAuth2Impl extends AbsOAuth2 {

    @Override
    protected ThirdPartyEnum supportThirdPartyEnum() {
        return ThirdPartyEnum.GITHUB;
    }

    @Override
    protected String getThirdEmail(String url, OAuth2AccessTokenBO accessTokenBo) {
        OAuth2UserInfo oAuth2UserInfo = RestTemplateUtil.doGet(url, getHttpHeaders(accessTokenBo.getAccessToken()), null, OAuth2UserInfo.class);
        return oAuth2UserInfo.getEmail();
    }

    @Override
    protected String getThirdUserName(String url, OAuth2AccessTokenBO accessTokenBo) {
        OAuth2UserInfo oAuth2UserInfo = RestTemplateUtil.doGet(url, getHttpHeaders(accessTokenBo.getAccessToken()), null, OAuth2UserInfo.class);
        return oAuth2UserInfo.getName();
    }

    private HttpHeaders getHttpHeaders(String accessToken) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
        headers.add("X-GitHub-Api-Version", "2022-11-28");
        return headers;
    }

}
